<template>
  <div class="following-container">
    <NavBar title="TA关注的" backgroundColor="#161622">
      <template #left>
        <div class="left" @click="goBack">
          <Icon name="zuojiantou" size="18" color="#fff"></Icon>
        </div>
      </template>
    </NavBar>
    <div class="following-list">
      <div class="following-item" v-for="user in followingList" :key="user.userId">
        <div class="avatar" @click="goToUserProfile(user.userId)">
          <img :src="user.userAvatar" :alt="user.userNickname" />
        </div>
        <div class="info">
          <div class="name">{{ user.userNickname }}</div>
          <div class="desc">{{ user.userDesc }}</div>
          <div class="time">{{ user.formattedTime }}</div>
        </div>
        <div class="follow-button" @click="toggleFollow(user)" :class="{
          'active': user.myRelation === 'follow',
          'default': user.myRelation === 'none'
        }">
          <template v-if="user.myRelation === 'none'">关注</template>
          <template v-else-if="user.myRelation === 'follow'">已关注</template>
          <template v-else-if="user.myRelation === 'me'">我</template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useDateFormat } from '@/composables/useDateFormat'
import NavBar from '@/components/Common/NavBar/index.vue'
import Icon from '@/components/Common/Icon/index.vue'
import { getTAsFocusListAPI, triggerFollowAPI } from '@/api/Home'
import { useUserIDStore } from '@/stores/UserID'

import { useRouter, useRoute } from 'vue-router'
const route = useRoute()
const router = useRouter()

const friendId = route.params.friendId
console.log('friendId', friendId)



const emit = defineEmits(['update:modelValue'])

const goBack = () => {
  // 返回到用户详情页，而不是使用go(-1)
  router.push({ 
    name: 'UserDetails', 
    params: { friendId },
    query: { from: route.query.from || 'home' } // 保持来源信息
  })
}

const userIDStore = useUserIDStore()
const currentUserId = userIDStore.userInfo?.userId
const followingList = ref([])


// 获取我关注的列表
const fetchFollowingList = async () => {
  if (!currentUserId) return
  try {
    const res = await getTAsFocusListAPI(friendId, currentUserId)
    console.log(res)
    if (res.code === 200) {
      followingList.value = res.data.map(user => ({
        ...user,
        userAvatar: 'http://43.138.15.137:3000' + user.userAvatar,
        formattedTime: useDateFormat(user.createdAt, 'YYYY-MM-DD').formatted,
      }))
    }
  } catch (error) {
    console.error('获取关注列表失败:', error)
  }
}

// 切换关注状态（取消 or 重新关注）
const toggleFollow = async (user) => {
  // 找到当前用户在列表中的索引
  const index = followingList.value.findIndex(u => u.userId === user.userId)
  if (index === -1) return // 未找到用户

  try {
    const res = await triggerFollowAPI(friendId, user.userId)
    if (res.code === 200) {
      // 更新用户状态
      followingList.value[index].myRelation = followingList.value[index].myRelation === 'none' ? 'follow' : 'none'
    }
    console.log(res)
  } catch (error) {
    console.error('关注操作失败:', error)
    // 可选：toast 提示
  }
}

// 跳转用户详情页
const goToUserProfile = (friendId) => {
  router.push({ name: 'UserDetails', params: { friendId } })
}

onMounted(() => {
  fetchFollowingList()
})
</script>

<style lang="scss" scoped>
.following-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #161622;
  padding-bottom: 35px;
  z-index: 2026;
  overflow-y: auto;


  .following-list {
    padding: 10px;

    .following-item {
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      .avatar {
        width: 45px;
        height: 45px;
        border-radius: 50%;
        margin-right: 10px;

        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
          object-fit: cover;
        }
      }

      .info {
        flex: 1;

        .name {
          font-size: 14px;
          font-weight: bold;
          color: #fff;
          line-height: 1;
        }

        .desc {
          font-size: 12px;
          color: #fff;
          margin-bottom: 5px;
          font-weight: bold;
        }

        .time {
          font-size: 12px;
          color: #879394;
          font-weight: bold;
        }
      }

      .follow-button {
        width: 60px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        font-weight: bold;
        padding: 4px 8px;
        border-radius: 2px;
        white-space: nowrap;
        cursor: pointer;

        &.active {
          color: #fff;
          background-color: #393b44;
        }

        &.default {
          color: #fff;
          background-color: #f9355f;
        }
      }
    }
  }
}
</style>